package android;

import hibernate.Driverstab;
import hibernate.DriverstabDAO;


import hibernate.Orderstab;
import hibernate.OrderstabDAO;
import hibernate.Parkstab;
import hibernate.ParkstabDAO;

import java.io.IOException;
import java.io.OutputStream;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;




import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;




import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.json.JSONException;
import org.json.JSONObject;

import global.GlobalArgs;


import controller.WebServerEndpoint;

/**
 * Servlet implementation class OrderSpaceServlet
 */

public class OrderSpaceServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public OrderSpaceServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		doPost(request, response);

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	@SuppressWarnings("unchecked")
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("utf-8");
		JSONObject resultJson =new JSONObject();
		OutputStream out=response.getOutputStream();
		Boolean isOrderSuccess=false;


		String userIDstr=(String)request.getSession().getAttribute("userID");
		System.out.println("userIDstr  "+userIDstr+"put order !!!!!!!!!!!!!!!!!!!!!!");
		if(userIDstr==null)
		{

			try {
				resultJson.put("errorPoint", "session_userID_noget");
				sendFail(out,resultJson);
				return ;
			} catch (JSONException e) {

				e.printStackTrace();return;

			}

		}


		int orderParkID=-1;
		int orderTime=-1;
		int orderNumber=-1;
		int orderUserID=Integer.valueOf(userIDstr);


		try {
			JSONObject reciveJson=new JSONObject(request.getParameter("jsonString"));
			System.out.println("jsonString  "+reciveJson.toString());
			orderTime=Integer.valueOf(reciveJson.getString("orderTime"));
			orderNumber=Integer.valueOf(reciveJson.getString("orderNumber"));
			orderParkID=Integer.valueOf(reciveJson.getString("parkID"));

		} catch (JSONException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();

		}	

		if(orderTime==-1||orderNumber==-1||orderParkID==-1)
		{
			try {

				resultJson.put("errorPoint", "fail_parse_Paramter");
				sendFail(out,resultJson);
				return ;
			} catch (JSONException e) {

				e.printStackTrace();return;
			}
		}







		//����û�id�ǲ��Ǵ���		
		List<Driverstab> driversList=null;
		DriverstabDAO driverstabDAO=new DriverstabDAO();
		driverstabDAO.getSession().beginTransaction();
		try
		{

			String hql="from Driverstab as d where d.uuid = :uuid";
			Query result=driverstabDAO.getSession().createQuery(hql);



			result.setInteger("uuid",orderUserID);
			driversList=result.list();
		}
		catch(HibernateException e)
		{
			System.out.println("hibernate error in OrderSpaceServlet while query direrstab");
			e.printStackTrace();
		}
		finally
		{
			driverstabDAO.getSession().getTransaction().commit();
			driverstabDAO.getSession().close();

		}
		if(driversList.size()!=1)
		{
			try {

				resultJson.put("errorPoint", "session_userID_noExist");
				sendFail(out, resultJson);
				System.out.println("!!!!!!!!!!sos driversList.size()!=1!!!!!!!!!!!!!!!!!");
				return;
			} catch (JSONException e) {

				e.printStackTrace();return;
			}
		}
		//���ͣ����id�Ƿ����,�����ڰѽ���Ԥ��ʱ���¼����

		int maxOrderTime=-1;
		double price=-1;
		List<Parkstab> parksList=null;
		ParkstabDAO parkstabDAO=new ParkstabDAO();
		parkstabDAO.getSession().beginTransaction();
		try
		{

			String hql="from Parkstab as p where p.uuid = :uuid";
			Query result=parkstabDAO.getSession().createQuery(hql);



			result.setInteger("uuid",orderParkID);
			parksList=result.list();
		}
		catch(HibernateException e)
		{
			System.out.println("hibernate error in OrderSpaceServlet while query parksTab");
			e.printStackTrace();
		}
		finally
		{
			parkstabDAO.getSession().getTransaction().commit();
			parkstabDAO.getSession().close();

		}
		if(parksList.size()!=1)
		{
			try {

				resultJson.put("errorPoint", "session_parkID_noExist");
				sendFail(out, resultJson);
				System.out.println("!!!!!!!!!!sos parksList.size()!=1!!!!!!!!!!!!!!!!!");
				return;
			} catch (JSONException e) {

				e.printStackTrace();return;
			}
		}
		else
		{
			maxOrderTime=parksList.get(0).getMaxOrderTime();
			price=parksList.get(0).getPrice();
		}


		if(maxOrderTime==-1)
		{
			System.out.println("sos maxOrderTime==-1!!!!!!!!!!!!");
		}

		//���ʱ���Ƿ���Ԥ����

		boolean inOrderWindow=orderTime<maxOrderTime?true:false;

		if(!inOrderWindow)
		{
			try {

				resultJson.put("errorPoint", "time_out_renge");
				sendFail(out, resultJson);
				return;
			} catch (JSONException e) {

				e.printStackTrace();return;
			}
		}

		//��Ӷ���	
		Calendar nowTime=Calendar.getInstance();
		String nowTimeStr = null;
		OrderstabDAO orderstabDAO=new OrderstabDAO();
		orderstabDAO.getSession().beginTransaction();
		try
		{

			Orderstab orderstab =new Orderstab();
			orderstab.setParkstab(parksList.get(0));
			orderstab.setDriverstab(driversList.get(0));
			orderstab.setPrice(orderTime*price);
			orderstab.setOrderTime(orderTime);
			orderstab.setOrderNumber(orderNumber);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			nowTimeStr = sdf.format(nowTime.getTime());
			orderstab.setPushTime(Timestamp.valueOf(nowTimeStr));	
			nowTime.set(Calendar.HOUR, orderTime);
			nowTime.set(Calendar.MINUTE, orderNumber);
			orderstab.setState(GlobalArgs.ORDERWAITACCEPT);

			orderstabDAO.attachDirty(orderstab);
			try {
				resultJson.put("orderResult","succeed");
				resultJson.put("errorPoint", "none");
				isOrderSuccess=true;
			} catch (JSONException e) {

				e.printStackTrace();
			}


		}  
		catch(HibernateException e)
		{
			System.out.println("hibernate error in OrderSpaceServlet");
			e.printStackTrace();
		}
		finally
		{
			orderstabDAO.getSession().getTransaction().commit();
			orderstabDAO.getSession().close();

		}



		if(isOrderSuccess)
		{



			orderstabDAO.getSession().beginTransaction();

			String getTheNewOrder="from Orderstab as o where  o.parkstab =:parkUUID and "
					+ "o.driverstab = :driverUUID and "
					+ "o.price = :price and "
					+ "o.orderTime = :orderTime and "
					+ "o.pushTime = :pushTime and "
					+ "o.orderNumber = :orderNumber";
			Query result=parkstabDAO.getSession().createQuery(getTheNewOrder);
			result.setInteger("driverUUID", driversList.get(0).getUuid());
			result.setInteger("parkUUID", parksList.get(0).getUuid());
			result.setDouble("price", orderTime*price);
			result.setInteger("orderNumber", orderNumber);
			result.setInteger("orderTime", orderTime);
			result.setTimestamp("pushTime", Timestamp.valueOf(nowTimeStr));
			try
			{

				List<Orderstab> orderList=result.list();
				Orderstab orderstab =orderList.get(0);
				WebServerEndpoint.orderRequest(driversList.get(0).getUuid(), parksList.get(0).getUuid(), orderstab.getUuid());

				


			}  
			catch(HibernateException e)
			{
				System.out.println("hibernate error in OrderSpaceServlet");
				e.printStackTrace();
			}
			finally
			{
				orderstabDAO.getSession().getTransaction().commit();
				orderstabDAO.getSession().close();

			}

		}


		out.write(resultJson.toString().getBytes("utf-8"));
		out.flush();
		out.close();
		return;

	}



	private void sendFail (OutputStream out,JSONObject toSend) throws ServletException, IOException,JSONException
	{
		toSend.put("orderResult","fail");
		out.write(toSend.toString().getBytes("utf-8"));
		out.flush();
		out.close();
		return;
	}

}

